﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using System.IO;
using System.IO.IsolatedStorage;
using TwitterBEIS_SL3_SLApp.TwitterProxyReference;

namespace TwitterBEIS_SL3_SLApp.Views
{
    public partial class Login : Page
    {
        public Login()
        {
            InitializeComponent();
        }

        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            Storage.ReadSecret();

            if (Storage.Remember)
            {
                UserName.Text = Storage.UserName;
                Password.Text = Storage.Password;
                RememberChk.IsChecked = Storage.Remember;
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(UserName.Text) || string.IsNullOrEmpty(Password.Text))
            {
                return;
            }

            TwitterProxyReference.TwitterProxyClient proxy = TwitterProxy.GetProxy();
            proxy.VerifyCredentialsCompleted += new EventHandler<TwitterBEIS_SL3_SLApp.TwitterProxyReference.VerifyCredentialsCompletedEventArgs>(proxy_VerifyCredentialsCompleted);
            InfoText.Text = "Authenticating by Twitter...";
            SigninBtn.IsEnabled = false;
            proxy.VerifyCredentialsAsync(UserName.Text,Password.Text);
        }

        void proxy_VerifyCredentialsCompleted(object sender, TwitterBEIS_SL3_SLApp.TwitterProxyReference.VerifyCredentialsCompletedEventArgs e)
        {
            try
            {
                Storage.SaveSecret(e.Result,UserName.Text, Password.Text, (bool)RememberChk.IsChecked);
                (Parent as Frame).Navigate(new Uri("/Views/Home.xaml", UriKind.Relative));
                if (Storage.TweetsCount() == 0)
                {
                    Storage.SyncData();
                }
                else
                {
                    Storage.PostTweets();
                }
            }
            catch
            {
                InfoText.Style = App.Current.Resources["ErrorMessageStyle"] as Style;
                InfoText.Text = "An error occurs on login. Please try again later.";
            }
            finally
            {
                SigninBtn.IsEnabled = true;
            }
        }
    }
}
